﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.RightsManagement;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using ExamSelfTouch.Message;
using ExamSelfTouch.Model;
using ExamSelfTouch.Tools;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using Xc.Core.Tools;
using System.Configuration;

namespace ExamSelfTouch.ViewModel
{
    public class MainViewModel : ViewModelBase
    {
        #region 命令
        public RelayCommand ShowInputNumber { get; private set; }
        public RelayCommand ShowQuestionImage { get; private set; }
        public RelayCommand Return { get; private set; }
        #endregion

        #region 私有属性
        private string _examNumber;
        private string _name;
        private string _examType;
        private bool _isInputover;
        private bool _isCorrectResult;
        private QuestionInfo _imageQuestion { get; set; }
        private QuestionInfo _textQuestion { get; set; }
        private QuestionInfo _videoQuestion { get; set; }

        private ImageSource _header { get; set; }

        
        #endregion

        #region 公开属性
        /// <summary>
        /// 输入的准考证
        /// </summary>
        public string ExamNumber
        {
            get { return _examNumber; }
            set
            {
                _examNumber = value;
                RaisePropertyChanged("ExamNumber");
                if (!String.IsNullOrEmpty(_examNumber))
                {
                    //准考证改变进行调用远程接口获取数据
                    SetExamStuInfo(_examNumber);
                }
            }
        }


        /// <summary>
        /// 学生姓名
        /// </summary>
        public string Name
        {
            get { return _name; }
            set
            {
                _name = value;
                RaisePropertyChanged("Name");
            }
        }


        /// <summary>
        /// 考试类别
        /// </summary>
        public string ExamType
        {
            get { return _examType; }
            set
            {
                _examType = value;
                RaisePropertyChanged("ExamType");
            }
        }
         
        /// <summary>
        /// 是否输入完准考证
        /// </summary>
        public bool IsInputOver
        {
            get { return _isInputover; }
            set { _isInputover = value;
                RaisePropertyChanged("IsInputOver"); }
        }

        private bool _isinputing=true;

        public bool IsInputing
        {
            get { return _isinputing; }
            set { _isinputing = value;
                
                RaisePropertyChanged("IsInputing"); }
        }


        private string _version;
        public string Version
        {
            get { return _version; }
            set { _version = value; RaisePropertyChanged("Version"); }
        }
        


        /// <summary>
        /// 头像
        /// </summary>
        public ImageSource Header
        {
            get { return _header; }
            set
            {
                _header = value;
                RaisePropertyChanged("Header");
            }
        }

        public bool IsCorrectResult
        {
            get { return _isCorrectResult; }
            set { _isCorrectResult = value; RaisePropertyChanged("IsCorrectResult"); }
        }
        

        /// <summary>
        /// 已答题集合
        /// </summary>
        public List<SendQuestionOverAnswer> QuestionOverAnswers { get; set; }
        #endregion

        /// <summary>
        /// 获取考生信息
        /// </summary>
        /// <param name="examNumber"></param>
        private async void SetExamStuInfo(string examNumber)
        {
            Messenger.Default.Send<SendSingleWindow>(new SendSingleWindow(EnumUseWindowType.Show));
            string msg = string.Empty;
            try
            {
                    string getexaminee_url = string.Format("GetExaminee?nr={0}&session={1}", examNumber,HttpBase2.SESSION);
                    var result = await HttpBase2.GetAsync<ExamineeInfoApi>(getexaminee_url);
                    string log_msg = string.Format("获取考生:{0}，返回值{1}", this.ExamNumber, result.status);

                    LogTool.WriteInfoLog(log_msg);
                
                if (result.status == 0 && result.examinee != null)
                    {
                        
                        if (!result.subject.Contains("xc"))
                        {
                            FormTools.ShowMsgWindow("该学员已完成考试，不能重复考试");
                        }
                        else
                        {
                            IsCorrectResult = true;
                            IsInputOver = true;
                            IsInputing = false;
                            //等待返回结果
                            Name = result.examinee.name;
                            ExamType = result.examinee.WTAdded;
                            if (!String.IsNullOrEmpty(result.examinee.photo))
                                GetHeader(result.examinee.photo);
                            else
                            {
                                Header = new BitmapImage(new Uri(@"Source\Images\nophoto.jpg", UriKind.Relative));
                            }
                        }
                    }
                    else
                        FormTools.ShowMsgWindow("未找到学员信息");
                
              
            }
            catch (Exception ex)
            {
                GetMessage(ex, ref msg);

                FormTools.ShowMsgWindow(msg);
            }

            
            Messenger.Default.Send<SendSingleWindow>(new SendSingleWindow(EnumUseWindowType.Hide));
        }

        private void GetHeader(string photoStr)
        {
            byte[] arr = Convert.FromBase64String(photoStr);
            MemoryStream ms = new MemoryStream(arr);
            Bitmap bmp = new Bitmap(ms);
            ms.Close();
            Header = ImageTools.BitmapToBitmapImage(bmp);
        }


        public MainViewModel()
        {
            ShowInputNumber = new RelayCommand(ShowInputNumberWindow);
            ShowQuestionImage = new RelayCommand(ShowQuestionImageWindow);
            Return = new RelayCommand(RetrunCommandExec);
            QuestionOverAnswers = new List<SendQuestionOverAnswer>();
         
           

            //更改准考证号
            Messenger.Default.Register<SendNumberMessage>(this, (msg) =>
            {
                if (!String.IsNullOrEmpty(msg.Number))
                {
                    ExamNumber = msg.Number;
                }
            });

            ////处理消息提示窗口
            //Messenger.Default.Register<SendMsg>(this, (msg) =>
            //{

            //});

            //处理普通窗体的弹出与关闭
            Messenger.Default.Register<SendWindow>(this, (msg) =>
            {
                if (msg.Window != null)
                {
                    if (msg.WindowType == EnumUseWindowType.Show)
                        msg.Window.Show();
                    else
                        msg.Window.Close();
                }
            });

            //处理特殊的单例窗口的弹出与关闭
            //Messenger.Default.Register<SendSingleWindow>(this, (single) =>
            //{
            //    var isShow = single.UseType == EnumUseWindowType.Show;
            //    switch (single.SingleWindow)
            //    {
            //        case EnumSingleWindow.LoadingWindow:
            //            FormTools.LoadingWindow(isShow);
            //            break;
            //        case EnumSingleWindow.QuestionImageWindow:
            //            FormTools.QuestionImageWindow(isShow);
            //            break;
            //        case EnumSingleWindow.QuestionTextWindow:
            //            FormTools.QuestionTextWindow(isShow);
            //            break;
            //        case EnumSingleWindow.QuestionVideoWindow:
            //            FormTools.QuestionVideoWindow(isShow);
            //            break;
            //        case EnumSingleWindow.MainWindow://added by gzx
            //            FormTools.MainWindow(isShow);
            //            break;
            //    }
            //});

            //处理单选
            Messenger.Default.Register<SendQuestionOverAnswer>(this, (question) =>
            {
                var single = QuestionOverAnswers.SingleOrDefault(t => t.QuestionId == question.QuestionId);
                if (single != null)
                {
                    if (single.SelectAnswer != question.SelectAnswer)
                    {
                        QuestionOverAnswers.Remove(single);
                        QuestionOverAnswers.Add(question);
                    }
                }
                else
                    QuestionOverAnswers.Add(question);
            });

            //处理多选
            Messenger.Default.Register<List<SendQuestionOverAnswer>>(this, (answers) =>
            {
                if (answers.Count == 0) return;
                //先移除本题之前的答案，然后添加新选项
                var main_answers = QuestionOverAnswers.Where(t => t.QuestionId == answers[0].QuestionId).ToList();
                foreach (var item in main_answers)
                {
                    QuestionOverAnswers.Remove(item);
                }
                QuestionOverAnswers.AddRange(answers);

            });

            //处理总得字符串消息
            Messenger.Default.Register<string>(this, CalcScore);

            //Messenger.Default.Register<String>(this, (msg) =>
            //{
            //    //提交试卷命令,计算成绩
            //    if (msg == "CommitExam")
            //    {
            //        int allScrore = 0;
            //        var text = QuestionOverAnswers.SingleOrDefault(t => t.QuestionType == EnumQuestionType.Text);
            //        var textScore = (text != null && _textQuestion != null && text.SelectAnswer == _textQuestion.Answer.ToUpper()) ? 6 : 0;
            //        //var image = QuestionOverAnswers.SingleOrDefault(t => t.QuestionType == EnumQuestionType.Image);
            //        //var video = QuestionOverAnswers.SingleOrDefault(t => t.QuestionType == EnumQuestionType.Video);
                    
            //        //var imageScore = (image != null && _imageQuestion != null && image.SelectAnswer == _imageQuestion.Answer.ToUpper()) ? 6 : 0;
            //        //var videoScore = (video != null && _videoQuestion != null && video.SelectAnswer == _videoQuestion.Answer.ToUpper()) ? 8 : 0;
            //        //allScrore = textScore + imageScore + videoScore;
            //        //FormTools.ShowMsgWindow(String.Format("提交成功，共获取{0}分", allScrore));


            //        var images = QuestionOverAnswers.Where(i => i.QuestionType == EnumQuestionType.Image).Select(i=>i.SelectAnswer).ToList();
            //        var image_answers = string.Join("", images);
            //        var image_socre = image_answers == _imageQuestion.Answer.ToUpper() ? 6 : 0;

            //        var videos = QuestionOverAnswers.Where(i => i.QuestionType == EnumQuestionType.Video).Select(i => i.SelectAnswer).ToList();
            //        var video_answers = string.Join("", videos);
            //        var video_score = video_answers == _videoQuestion.Answer.ToUpper() ? 8 : 0;

            //        allScrore = textScore + image_socre + video_score;

            //        //ShowMessage(allScrore);

            //        //TODO: 
            //        UploadScore(textScore, image_socre, video_score);

            //        //执行清空操作
            //        ClearInfo();
            //        QuestionOverAnswers = new List<SendQuestionOverAnswer>();

            //        FormTools.ClearAllSingleWindow();
            //        return;
            //    }
            //});

            InitVersion();
        }

        private void InitVersion()
        {
            Version = ConfigurationManager.AppSettings["VERSION"];
        }


        private async void CalcScore(string msg)
        {
            if (msg == "CommitExam")
            {
                int allScrore = 0;
                var text = QuestionOverAnswers.SingleOrDefault(t => t.QuestionType == EnumQuestionType.Text);
                var textScore = (text != null && _textQuestion != null && text.SelectAnswer == _textQuestion.Answer.ToUpper()) ? 6 : 0;

                var images = QuestionOverAnswers.Where(i => i.QuestionType == EnumQuestionType.Image).Select(i => i.SelectAnswer).ToList();
                var image_answers = string.Join("", images);
                var image_socre = image_answers == _imageQuestion.Answer.ToUpper() ? 6 : 0;

                var videos = QuestionOverAnswers.Where(i => i.QuestionType == EnumQuestionType.Video).Select(i => i.SelectAnswer).ToList();
                var video_answers = string.Join("", videos);
                var video_score = video_answers == _videoQuestion.Answer.ToUpper() ? 8 : 0;

                allScrore = textScore + image_socre + video_score;
                await UploadScore(textScore, image_socre, video_score);
                //执行清空操作
                ClearInfo();
                QuestionOverAnswers = new List<SendQuestionOverAnswer>();

                FormTools.ClearAllSingleWindow();
                return;
            }
            
        }
        private async Task UploadScore(int textScore, int imageScore, int videoScore)
        {
            Messenger.Default.Send<SendSingleWindow>(new SendSingleWindow(EnumUseWindowType.Show));
            var allScrore = textScore + imageScore + videoScore;
            ScoreData data = new ScoreData()
            {
                session = HttpBase2.SESSION,
                nr = this.ExamNumber,
                items = new List<score>(){
                        new score(){ name = "xc_1_"+_textQuestion.Content, value=textScore},
                        new score(){ name = "xc_2_"+_imageQuestion.Content, value=imageScore},
                        new score(){ name = "xc_3_"+_videoQuestion.Content, value=videoScore}, 
                        new score(){ name = "xc_sum", value=allScrore}, 
                   }
            };
            try
            {//C:\Users\Administrator\Source\Repos\ExamSelf_wh\ExamSelfSolution\ExamSelfTouch\Source\
                var rdata = await HttpBase2.PostAsJsonAsync<ResultData>("Score", data);
                string log_msg = string.Format("考生{0}上传分数，返回值{1}",this.ExamNumber, rdata.status);

                LogTool.WriteInfoLog(log_msg);

                switch (rdata.status)
                {
                    case 0:
                        FormTools.ShowMsgWindow(string.Format("上传成绩完成, 得分：{0}", allScrore));
                        break;
                    case -1:
                        FormTools.ShowMsgWindow("身份验证失败，请尝试重录系统");
                        break;
                    case -2:
                        FormTools.ShowMsgWindow("参数异常");
                        break;
                    case -3:
                        FormTools.ShowMsgWindow("服务器内部错误，请联系管理员");
                        break;
                    case 2:
                        FormTools.ShowMsgWindow("未知的分数项代码");
                        break;
                }
            }
            catch (Exception)
            {
                //SaveScoreToLocal(data.items);
                FormTools.ShowMsgWindow("上传过程中遇到错误，请确认网络畅通");
            }
            Messenger.Default.Send<SendSingleWindow>(new SendSingleWindow(EnumUseWindowType.Hide));
        }

        //private void SaveScoreToLocal(IList<score> list)
        //{
        //    foreach (var item in list)
        //    {
        //        WebScore score = new WebScore()
        //        {
        //            name = item.name,
        //            value = item.value,
        //            titleId = this.ExamNumber
        //        };
        //        score.Save();
        //    }     
        //}


        private void ClearInfo()
        {
            ExamNumber = "";
            Name = "";
            ExamType = "";
            Header = null;
            _imageQuestion = null;
            _textQuestion = null;
            _videoQuestion = null;
            _header = null;
            IsInputing = true;
            IsInputOver = false;
            IsCorrectResult = false;
            Messenger.Default.Send<SendNumberMessage>(new SendNumberMessage(""));
        }

        private void RetrunCommandExec()
        {
            ClearInfo();
            
        }

        private async void ShowQuestionImageWindow()
        {
            //确定姓名有内容，再调取题库
            if (!String.IsNullOrEmpty(Name))
               await GetQuestionAsync();
        }

        private async Task GetQuestionAsync()
        {
            Messenger.Default.Send<SendSingleWindow>(new SendSingleWindow(EnumUseWindowType.Show));
            string url = string.Format("Question/GetQuestion?worktype={0}", this.ExamType);
            var questions = await HttpBase.GetAsync<List<QuestionInfo>>(url);
            if (questions == null)
            {
                FormTools.ShowMsgWindow("未找到合适的题目");
                Messenger.Default.Send<SendSingleWindow>(new SendSingleWindow(EnumUseWindowType.Hide));
                return;
            }
            var qcount = questions.Count(i => i != null);
            if (qcount < questions.Count)
            {
                FormTools.ShowMsgWindow("未找到合适的题目");
                Messenger.Default.Send<SendSingleWindow>(new SendSingleWindow(EnumUseWindowType.Hide));
                return;
            }

            //循环添加变量
            var ids = new List<int>();
            questions.ForEach(i => ids.Add(i.Id));

            var options = await HttpBase.PostAsJsonAsync<List<OptionsInfo>>("Question/GetOptions", ids);

            //如果超过3题
            if (questions.Count >= 3)
            {
                //启动第一个页面
                Messenger.Default.Send<SendSingleWindow>(new SendSingleWindow(EnumUseWindowType.Show, EnumSingleWindow.QuestionTextWindow));
                //接着实例化另外两个页面，并隐藏起来
                Messenger.Default.Send<SendSingleWindow>(new SendSingleWindow(EnumUseWindowType.Hide, EnumSingleWindow.QuestionImageWindow));
                Messenger.Default.Send<SendSingleWindow>(new SendSingleWindow(EnumUseWindowType.Hide, EnumSingleWindow.QuestionVideoWindow));

                
            }
            else
            {
                FormTools.ShowMsgWindow("未找到合适的题目");
                Messenger.Default.Send<SendSingleWindow>(new SendSingleWindow(EnumUseWindowType.Hide));
                return;
            }

            ExamineeInfo examineeInfo = new ExamineeInfo()
            {
                ExamNumber = this.ExamNumber,
                ExamType = this.ExamType,
                Header = this.Header,
                Name = this.Name
            };

            //分配题目分别发送给三个页面
            var imageQuestion = questions.SingleOrDefault(t => t.QuestionType == EnumQuestionType.Image);
            if (imageQuestion != null)
            {
                var imageOptions = options.Where(t => t.QuestionID == imageQuestion.Id).ToList();
                if (imageOptions.Count > 0)
                    Messenger.Default.Send<SendImageQuestion>(new SendImageQuestion(imageQuestion, imageOptions, examineeInfo));
                _imageQuestion = imageQuestion;
            }

            var textQuestion = questions.SingleOrDefault(t => t.QuestionType == EnumQuestionType.Text);
            if (textQuestion != null)
            {
                var textOptions = options.Where(t => t.QuestionID == textQuestion.Id).ToList();
                if (textOptions.Count > 0)
                    Messenger.Default.Send<SendTextQuestion>(new SendTextQuestion(textQuestion, textOptions, examineeInfo));
                _textQuestion = textQuestion;
            }

            var videoQuestion = questions.SingleOrDefault(t => t.QuestionType == EnumQuestionType.Video);
            if (videoQuestion != null)
            {
                var videoOptions = options.Where(t => t.QuestionID == videoQuestion.Id).ToList();
                if (videoOptions.Count > 0)
                    Messenger.Default.Send<SendVideoQuestion>(new SendVideoQuestion(videoQuestion, videoOptions, examineeInfo));
                _videoQuestion = videoQuestion;
            }




            Messenger.Default.Send<SendSingleWindow>(new SendSingleWindow(EnumUseWindowType.Hide));
        }

        private void ShowInputNumberWindow()
        {
            new InputCardNoWindow().Show();
        }


        private void GetMessage(Exception ex, ref string msg)
        {
            if (ex.InnerException != null)
            {
                GetMessage(ex.InnerException, ref msg);
            }
            else
            {
                msg = ex.Message;
            }
        }

        
    }
}
